import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, Subject } from 'rxjs';
import { catchError, filter, map } from 'rxjs/operators';
import { SERVER_API_URL, USER_API_URL } from 'app/app.constants';
// import { Equipment, Result, Page, EquipmentType } from './interface/interface';
// import { LaneGroup } from 'app/public';
// import { ToolsService } from 'app/share';
// import { JUNCTIONM_API_URL, EQUIPMENTM_API_URL } from 'app/app.constants';
import { Router } from '@angular/router';
import { ConfigService } from 'app/config/config.service';
import * as moment from 'moment';

@Injectable({
    providedIn: 'root'
})
export class DataManagementService {
    // private apiUrl_equip_online = this.config.apiUrl.user;
    // private apiUrl_equip_online = USER_API_URL;
    private apiUrl_equip_online = this.config.apiUrl.report + '/vnqnreportmgt/trafficReport/get';
    private apiUrl_datauip_online = this.config.apiUrl.report + '/vnqnreportmgt/trafficReport/getPagingData';
    private apiUrl_enum_online = this.config.apiUrl.enum;
    private apiUrl_user_online = this.config.apiUrl.user;
    // private handleError: HandleError;

    private _dataConfigData: any;
    configDataExsited = false;

    get dataConfigData() {
        return this._dataConfigData;
    }

    set dataConfigData(data) {
        this._dataConfigData = data;
    }

    constructor(private http: HttpClient, private router: Router, private config: ConfigService) {}
    /**
     * get lane config info
     * @param params { juncId: string , isTemp: 0temp??1offcial }
     */

    // 获取Traffic Data Report报表数据
    getTraDataRep(queryData): Observable<any> {
        const url = `${this.apiUrl_equip_online}?queryNO=001&paras=${queryData}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Traffic Data Report表格数据
    getTraDataRepTable(queryData, pageNum, pageSize): Observable<any> {
        const url = `${this.apiUrl_datauip_online}?queryNO=001&paras=${queryData}&pageNum=${pageNum}&pageSize=${pageSize}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Traffic Accident Report报表数据
    getTraAccRep(queryData): Observable<any> {
        const url = `${this.apiUrl_equip_online}?queryNO=002&paras=${queryData}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Traffic Accident Report报表数据
    getTraAccRepTable(queryData, pageNum, pageSize): Observable<any> {
        const url = `${this.apiUrl_datauip_online}?queryNO=002&paras=${queryData}&pageNum=${pageNum}&pageSize=${pageSize}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Intersection Traffic Volume Report数据
    getVolumeRep(queryData): Observable<any> {
        const url = `${this.apiUrl_equip_online}?queryNO=004&paras=${queryData}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Intersection Traffic Volume Report数据
    getConRep(queryData): Observable<any> {
        const url = `${this.apiUrl_equip_online}?queryNO=005&paras=${queryData}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Technical Alarm Report数据
    getAlarmRep(queryData): Observable<any> {
        const url = `${this.apiUrl_equip_online}?queryNO=006&paras=${queryData}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Technical Alarm Report 子数据
    getAlarmChildRep(queryData): Observable<any> {
        const url = `${this.apiUrl_equip_online}?queryNO=007&paras=${queryData}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取Road Congestion Report数据
    getRoadRep(queryData): Observable<any> {
        const url = `${this.apiUrl_equip_online}?queryNO=003&paras=${queryData}`; // 查询参数
        return this.http.get<any>(url);
    }

    // 获取road和site下拉框数据
    getAllEnumInfo(): Observable<any> {
        const url = `${this.apiUrl_enum_online}/vnqnenummgt/user/getAllEnumInfo`; // 查询参数
        return this.http.get<any>(url);
    }
    // 获取用户列表
    getAllUser(param): Observable<any> {
        return this.http.post<any>(this.apiUrl_user_online + '/userMgt/user/getAllUserInfoByPage', param);
    }
    /**
     * equipment bind
     * @param params { Equipment }
     */

    private handleError<T>(operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {
            // TODO: send the error to remote logging infrastructure
            console.error(error); // log to console instead

            // TODO: better job of transforming error for user consumption
            this.log(`${operation} failed: ${error.message}`);

            // Let the app keep running by returning an empty result.
            return of(result as T);
        };
    }
    private log(message: string) {}
    /**
     * generateAllData
     * @param params 通过后台数据生成完整时间段数据
     */
    generateAllData(interval: number, data: Array<any>, timeRange: string, detectorIdName?: string) {
        // name 用来判断是否有多个设备
        if (data && data.length !== 0) {
            if (detectorIdName) {
                // 需要按照不同的设备类型生成不同的数组
                const detectorTypeMap = new Map(); // 构建一个保存所有设备的种类的Map
                const arrList = [];
                const arrResult = [];
                data.forEach(item => {
                    if (!detectorTypeMap.has(item[detectorIdName])) {
                        detectorTypeMap.set(item[detectorIdName], item[detectorIdName]);
                    }
                });
                for (const key of detectorTypeMap.keys()) {
                    const detectorDataList = [];
                    data.forEach(item => {
                        if (item[detectorIdName] === key) {
                            detectorDataList.push(item);
                        }
                    });
                    arrList.push(this.generateData(detectorDataList, interval, timeRange, detectorIdName));
                }
                arrList.forEach(arr => {
                    arrResult.push(...arr);
                });
                return arrResult;
            } else {
                // 只有一种设备
                return this.generateData(data, interval, timeRange, detectorIdName);
            }
        } else {
            return [];
        }
    }
    generateData(data: Array<any>, interval: number, timeRange: string, detectorIdName?: string) {
        const intervalNum = 1440 / interval; // 需要生成的对象数组的长度
        const objectTemplate = this.cleanObj({ ...data[0] }, detectorIdName); // 根据现有数据生成一个对象模板
        const fixedDate = new Date(2019, 11, 12, 0, 0, 0);
        let fixedTime = fixedDate.getTime(); // 固定时间戳作为起始
        const resultArr = [];
        const startUserTime = timeRange.split('~')[0];
        const endUserTime = timeRange.split('~')[1];
        const startUserTimeStamp = new Date(
            2019,
            11,
            12,
            +startUserTime.split(':')[0],
            +startUserTime.split(':')[1],
            +startUserTime.split(':')[2]
        ).getTime();
        const endUserTimeStamp = new Date(
            2019,
            11,
            12,
            +endUserTime.split(':')[0],
            +endUserTime.split(':')[1],
            +endUserTime.split(':')[2]
        ).getTime();
        for (let i = 0; i < intervalNum; i++) {
            let fixedStartTime = fixedTime;
            let fixedEndTime = fixedTime + interval * 60 * 1000;
            if (fixedStartTime >= startUserTimeStamp && fixedEndTime <= endUserTimeStamp) {
                // 符合用户选择时间区间
            } else if (fixedStartTime <= startUserTimeStamp && fixedEndTime <= endUserTimeStamp && fixedEndTime > startUserTimeStamp) {
                // 左不在， 右在
                fixedStartTime = startUserTimeStamp;
            } else if (fixedStartTime >= startUserTimeStamp && fixedEndTime >= endUserTimeStamp && fixedStartTime < endUserTimeStamp) {
                // 右不在， 左在
                fixedEndTime = endUserTimeStamp;
            } else if (fixedStartTime < startUserTimeStamp && fixedEndTime > endUserTimeStamp) {
                // 包含
                fixedStartTime = startUserTimeStamp;
                fixedEndTime = endUserTimeStamp;
            } else {
                fixedTime = fixedTime + interval * 60 * 1000; // 将时间加在基础时间上
                continue;
            }
            const objStartTime = moment(fixedStartTime).format('HH:mm:ss');
            const objEndTime = moment(fixedEndTime).format('HH:mm:ss');
            fixedTime = fixedTime + interval * 60 * 1000; // 将时间加在基础时间上
            const objTime = `${objStartTime}~${objEndTime}`;
            const obj = { ...objectTemplate }; // 用模板对象生成当前时间的对象
            obj['interval_zone'] = objTime;
            resultArr.push(obj);
        }
        resultArr.forEach((resItem, i) => {
            // 效率算法需要优化 TODO
            data.forEach(oldItem => {
                if (oldItem['interval_zone'] === resItem['interval_zone']) {
                    resultArr[i] = { ...oldItem };
                }
            });
        });
        return resultArr;
    }
    cleanObj(objectTemplate: object, detectorIdName?: string) {
        // 初始化对象
        if (detectorIdName) {
            // 多设备
            for (const attr in objectTemplate) {
                if (attr !== detectorIdName && attr !== 'interval_zone') {
                    objectTemplate[attr] = '0';
                }
            }
            return objectTemplate;
        } else {
            for (const attr in objectTemplate) {
                if (attr !== 'interval_zone') {
                    objectTemplate[attr] = '0';
                }
            }
            return objectTemplate;
        }
    }
}
